package org.csu.chatserver.service.Impl;

import org.csu.chatserver.entity.dto.ClearHistoryDTO;
import org.csu.chatserver.entity.dto.HistoryMsgDTO;
import org.csu.chatserver.entity.pojo.SingleMessage;
import org.csu.chatserver.entity.vo.HistoryMsgVO;
import org.csu.chatserver.mapper.SingleMessageMapper;
import org.csu.chatserver.service.SingleMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.csu.chatserver.entity.dto.UnreadCountDTO;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SingleMessageServiceImpl implements SingleMessageService {

    @Autowired
    private SingleMessageMapper singleMessageMapper;

    @Override
    public void persistMsg(SingleMessage singleMessage) {
        singleMessageMapper.insert(singleMessage);
    }

    @Override
    public List<HistoryMsgVO> getHistoriesMsg(HistoryMsgDTO historyMsgDTO) {
        return singleMessageMapper.getHistoriesMsg(historyMsgDTO.getSenderId(),historyMsgDTO.getTargetId());
    }

    @Override
    public void markMessagesAsRead(int senderId, int targetId) {
        singleMessageMapper.markMessagesAsRead(senderId, targetId);
    }

    @Override
    public Map<Integer, Integer> getUnreadCounts(int myUserId) {
        return singleMessageMapper.getUnreadCounts(myUserId)
                .stream()
                .collect(Collectors.toMap(UnreadCountDTO::getSenderId,
                        UnreadCountDTO::getUnreadCount));
    }

    @Override
    public boolean clearChatHistory(ClearHistoryDTO dto) {
        // 参数校验
        if (dto.getSenderId() == null || dto.getTargetId() == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        // 执行删除操作
        return singleMessageMapper.clearHistory(dto.getSenderId(), dto.getTargetId()) > 0;
    }
}
